package com.mdd.front.controller;

import com.alipay.api.AlipayApiException;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderV3Request;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.mdd.common.core.AjaxResult;
import com.mdd.common.utils.IpUtil;
import com.mdd.common.utils.RequestUtil;
import com.mdd.front.service.pay.IH5PayService;
import com.mdd.front.validate.PaymentValidate;
import com.mdd.front.vo.wxpay.WxPayCreateOrderRequest;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author kn4im3
 * @date 2023/2/24 15:35
 */
@RestController
@RequestMapping("/api/pay/h5")
public class H5PayController {

    @Resource
    private IH5PayService h5PayService;

    @PostMapping("/prePay")
    public AjaxResult prePay(@Validated(value = WxPayCreateOrderRequest.create.class)
                                      @RequestBody WxPayCreateOrderRequest request) throws WxPayException, AlipayApiException {
        WxPayUnifiedOrderV3Request.SceneInfo sceneInfo = new WxPayUnifiedOrderV3Request.SceneInfo();
        WxPayUnifiedOrderV3Request.H5Info h5Info = new WxPayUnifiedOrderV3Request.H5Info();
        h5Info.setType(getH5InfoType());
        sceneInfo.setH5Info(h5Info);
        sceneInfo.setPayerClientIp(IpUtil.getIpAddress());
        request.setSceneInfo(sceneInfo);
        Object pay = h5PayService.prePay(request);
        return AjaxResult.success(pay);
    }

    private String getH5InfoType() {
        HttpServletRequest request = RequestUtil.handler();
        String userAgent = request.getHeader("User-Agent");
        if(userAgent.contains("Android")){//安卓手机
            return "Android";
        }else if(userAgent.contains("iPhone")||userAgent.contains("iPod")||userAgent.contains("iPad")){//苹果手机
            return "IOS";
        } else {
            return "wap";
        }
    }
}
